package com.example.microservice.common.utils;

import java.io.File;
import java.net.MalformedURLException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import com.redfin.sitemapgenerator.SitemapIndexGenerator;
import com.redfin.sitemapgenerator.W3CDateFormat;
import com.redfin.sitemapgenerator.WebSitemapGenerator;
import com.redfin.sitemapgenerator.WebSitemapUrl;

/**
 * This is Description
 *
 * @author sun
 * @date 2019/06/12
 * @Description 生成sitemap xml 文件工具类
 */
public class CreateSiteMapUtils {


    /**
     * 生成siteMap xml文件
     */
    public static void createSitemap() {
        String tempPath = "/home/seo";
        //String tempPath = System.getProperty("java.io.tmpdir") + File.separator + "/seo/";
        File file = new File(tempPath);
  /*  if (!file.exists()) {
        file.mkdirs();
    }*/
        String domain = "https://www.domain.com";


        try {
            WebSitemapGenerator g1 = WebSitemapGenerator.builder(domain, file)
                    .fileNamePrefix("article").build();
            Date date = new Date();
            for (int i = 1; i < 21; i++) {
                WebSitemapUrl url = new WebSitemapUrl.Options(domain + "/article/" + i).lastMod(date).build();
                g1.addUrl(url);
            }

            WebSitemapGenerator g2 = WebSitemapGenerator.builder(domain, file)
                    .fileNamePrefix("issue").build();
            Date date2 = new Date();
            for (int i = 1; i < 21; i++) {
                WebSitemapUrl url = new WebSitemapUrl.Options(domain + "/issue/" + i).lastMod(date2).build();
                g2.addUrl(url);
            }

            List<String> fileNames = new ArrayList<>();

            // 生成 sitemap 文件
            List<File> articleFiles = g1.write();
            articleFiles.forEach(e -> fileNames.add(e.getName()));
            List<File> issueFiles = g2.write();
            issueFiles.forEach(e -> fileNames.add(e.getName()));

            // 构造 sitemap_index 生成器
            W3CDateFormat dateFormat = new W3CDateFormat(W3CDateFormat.Pattern.DAY);
            SitemapIndexGenerator sitemapIndexGenerator = new SitemapIndexGenerator
                    .Options(domain, new File(tempPath + "sitemap_index.xml"))
                    .dateFormat(dateFormat)
                    .autoValidate(true)
                    .build();

            fileNames.forEach(e -> {
                try {
                    // 组装 sitemap 文件 URL 地址
                    sitemapIndexGenerator.addUrl(tempPath + e);
                } catch (MalformedURLException e1) {
                    e1.printStackTrace();
                }
            });

            // 生成 sitemap_index 文件
            sitemapIndexGenerator.write();

        } catch (MalformedURLException e) {
            e.printStackTrace();
        }
    }


}
